package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.util.Arrays;

import static com.shanxia.codec.Decoder.*;

/**
 * C -> S
 * 充电桩密码登入报文
 * 如果使用加密通信方式，桩发送此报文请求加密方式
 */
@Data
public class Cmd1202 extends ProtocolDataBase {

    public static final int MIN_SIZE = 48;

    private int v1;
    private int v2;
    private String pwd;                         // 桩登入服务器密码
    private int random;                         // 随机数
    private String aesSecretKey;                // 后续报文 AES 加密密钥

    public Cmd1202(){
        super.setCmd(1202);
    }

    public static Cmd1202 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd1202 cmd = new Cmd1202();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 16字节充电桩编码
        cmd.pwd = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 16), true);
        offset += 16;
        // 4字节随机数
        cmd.random = bytesToIntLittle(dataField, offset);
        offset += 4;
        // 24字节后续报文AES加密密钥
        cmd.aesSecretKey = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 24), true);
        return cmd;
    }

    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append("#cmd1202#").append("\n");
        buffer.append("v1:").append(v1).append("\n");
        buffer.append("v2:").append(v2).append("\n");
        buffer.append("桩登入服务器密码:").append(pwd).append("\n");
        buffer.append("随机数:").append(random).append("\n");
        buffer.append("后续报文 AES 加密密钥:").append(aesSecretKey).append("\n");
        return buffer.toString();
    }
}
